#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <dirent.h>

// 包含您项目的所有自定义头文件
#include "jpeglib.h"
#include "lcd.h"
#include "photo.h"
#include "ts.h"
#include "ASC16.h"

// ===================================================================
// UI宏定义，全新布局
// ===================================================================
#define LCD_DEVICE          "/dev/ubuntu_lcd"
#define IMAGE_DIR           "./res/imagefiles"

#define LCD_WIDTH           800
#define LCD_HEIGHT          480
#define BACKGROUND_COLOR    0x00202020 

// --- 新布局参数 ---
#define CONTROL_PANEL_WIDTH 70         // 左侧控制区宽度 (改小)
#define INFO_BAR_HEIGHT     40         // 顶部信息栏高度
#define PANEL_COLOR         0x00383838 // UI面板的背景色

// 根据上述参数自动计算内容区的尺寸和位置
#define VIEWPORT_X          CONTROL_PANEL_WIDTH
#define VIEWPORT_Y          INFO_BAR_HEIGHT
#define VIEWPORT_WIDTH      (LCD_WIDTH - CONTROL_PANEL_WIDTH)
#define VIEWPORT_HEIGHT     (LCD_HEIGHT - INFO_BAR_HEIGHT)

// 控制区按钮的Y坐标布局
#define BUTTON_PREV_Y       60
#define BUTTON_NEXT_Y       160
#define BUTTON_ZOOM_IN_Y    260
#define BUTTON_ZOOM_OUT_Y   360
#define BUTTON_HEIGHT       80
#define BUTTON_TEXT_COLOR   0xFFE0E0E0 // 按钮文字颜色

// ===================================================================
// 辅助函数声明
// ===================================================================
void draw_rect(int x, int y, int w, int h, int color);
void draw_text(int x, int y, const char *text, int color);
void get_image_dimensions(const char *filename, int *width, int *height);
void draw_ui_overlay(const char *filename, int img_width, int img_height);


// ===================================================================
// 主函数
// ===================================================================
int main() {
    // 1. 初始化
    int fd_lcd = open(LCD_DEVICE, O_RDWR);
    if (fd_lcd == -1) { /* ... 错误处理 ... */ return -1; }
    plcd = mmap(NULL, LCD_WIDTH * LCD_HEIGHT * 4, PROT_READ | PROT_WRITE, MAP_SHARED, fd_lcd, 0);
    if (plcd == MAP_FAILED) { /* ... 错误处理 ... */ return -1; }

    // 2. 加载图片列表
    Node *head = NULL;
    scanf_list(IMAGE_DIR, &head);
    if (head == NULL) { /* ... 错误处理 ... */ return -1; }

    Node *current_image = head;
    double zoom_factor = 1.0;

    // 3. 主事件循环
    while (1) {
        // A. 用干净的背景色填充整个屏幕
        brush_lcd(BACKGROUND_COLOR);

        // B. 在指定的“内容区(Viewport)”内绘制图片
        const char *filename = current_image->filename;
        if (strstr(filename, ".bmp")) {
            draw_bmp_with_scale(filename, zoom_factor, VIEWPORT_X, VIEWPORT_Y, VIEWPORT_WIDTH, VIEWPORT_HEIGHT);
        } else if (strstr(filename, ".jpg") || strstr(filename, ".jpeg")) {
            draw_jpeg_with_scale(filename, zoom_factor, VIEWPORT_X, VIEWPORT_Y, VIEWPORT_WIDTH, VIEWPORT_HEIGHT);
        }

        // C. 绘制独立的UI覆盖层 (控制区、信息区、按钮)
        int img_width, img_height;
        get_image_dimensions(filename, &img_width, &img_height);
        draw_ui_overlay(filename, img_width, img_height);

        // D. 等待并处理触摸输入
        struct postion touch_pos = ts_xy();
        int x = touch_pos.x;
        int y = touch_pos.y;
        
        // 只需检测控制面板内的点击
        if (x > 0 && x < CONTROL_PANEL_WIDTH) {
            if (y > BUTTON_PREV_Y && y < BUTTON_PREV_Y + BUTTON_HEIGHT) {
                if (current_image->prev) { current_image = current_image->prev; zoom_factor = 1.0; }
            } else if (y > BUTTON_NEXT_Y && y < BUTTON_NEXT_Y + BUTTON_HEIGHT) {
                if (current_image->next) { current_image = current_image->next; zoom_factor = 1.0; }
            } else if (y > BUTTON_ZOOM_IN_Y && y < BUTTON_ZOOM_IN_Y + BUTTON_HEIGHT) {
                if (zoom_factor < 4.0) zoom_factor += 0.2;
            } else if (y > BUTTON_ZOOM_OUT_Y && y < BUTTON_ZOOM_OUT_Y + BUTTON_HEIGHT) {
                if (zoom_factor > 0.2) zoom_factor -= 0.2;
            }
        }
    }
    
    // ... 清理代码 ...
    return 0;
}

// ===================================================================
// UI辅助函数的实现
// ===================================================================

void draw_rect(int x, int y, int w, int h, int color) {
    int i, j;
    for (j = y; j < y + h; j++) {
        for (i = x; i < x + w; i++) {
            draw_point(i, j, color);
        }
    }
}

void draw_text(int x, int y, const char *text, int color) {
    int i = 0;
    while (text[i] != '\0') {
        if (x + i * 8 < LCD_WIDTH) { // 防止绘制超出屏幕
            draw_8x16(x + i * 8, y, &szASC16[(unsigned char)text[i] * 16], color);
        }
        i++;
    }
}

void get_image_dimensions(const char *filename, int *width, int *height) {
    *width = 0; *height = 0;
    FILE *file = fopen(filename, "rb");
    if (!file) return;
    if (strstr(filename, ".bmp")) {
        fseek(file, 18, SEEK_SET);
        fread(width, 4, 1, file);
        fread(height, 4, 1, file);
    } else if (strstr(filename, ".jpg") || strstr(filename, ".jpeg")) {
        struct jpeg_decompress_struct cinfo;
        struct jpeg_error_mgr jerr;
        cinfo.err = jpeg_std_error(&jerr);
        jpeg_create_decompress(&cinfo);
        jpeg_stdio_src(&cinfo, file);
        jpeg_read_header(&cinfo, TRUE);
        *width = cinfo.image_width;
        *height = cinfo.image_height;
        jpeg_destroy_decompress(&cinfo);
    }
    fclose(file);
}

void draw_ui_overlay(const char *filename, int img_width, int img_height) {
    char info_text[200];
    
    // 1. 绘制左侧控制面板背景
    draw_rect(0, 0, CONTROL_PANEL_WIDTH, LCD_HEIGHT, PANEL_COLOR);
    
    // 2. 绘制顶部信息栏背景 (注意其X坐标起点)
    draw_rect(VIEWPORT_X, 0, VIEWPORT_WIDTH, INFO_BAR_HEIGHT, PANEL_COLOR);

    // 3. 居中绘制信息文字
    const char *short_name = strrchr(filename, '/');
    short_name = short_name ? short_name + 1 : filename;
    sprintf(info_text, "%s [%d x %d]", short_name, img_width, img_height);
    
    int text_width = strlen(info_text) * 8; // 计算文本像素宽度
    int text_start_x = VIEWPORT_X + (VIEWPORT_WIDTH - text_width) / 2; // 计算居中起始点
    draw_text(text_start_x, 12, info_text, BUTTON_TEXT_COLOR);

    // 4. 绘制按钮文字
    draw_text(18, BUTTON_PREV_Y + 32, "<<", BUTTON_TEXT_COLOR);
    draw_text(18, BUTTON_NEXT_Y + 32, ">>", BUTTON_TEXT_COLOR);
    draw_text(28, BUTTON_ZOOM_IN_Y + 32, "+", BUTTON_TEXT_COLOR);
    draw_text(28, BUTTON_ZOOM_OUT_Y + 32, "-", BUTTON_TEXT_COLOR);
}